package com.dong.designpattern.singleton;

/**
 * 单例模式 - 懒汉式2（lazy loading）
 * 虽然达到了按需初始化的目的，但却带来线程不安全的问题
 * 可以通过synchronized加锁解决，但也带来效率下降
 *
 * @author by jiweidong on 2021/11/16.
 */
public class Singleton04 {

    private static Singleton04 INSTANCE;

    private Singleton04() {

    }

    public static synchronized Singleton04 getInstance() throws InterruptedException {
        if (INSTANCE == null) {
//            Thread.sleep(1);
            INSTANCE = new Singleton04();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Singleton04.getInstance().hashCode());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
